package tree;

import java.util.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @ClassName LC102
 * @Description 层序遍历
 * @Author ZJX
 * @Date 2024/10/22 10:26
 * @Version 1.0
 */



class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
    this.val = val;
    this.left = left;
    this.right = right;
    }
}



//      https://leetcode.cn/problems/binary-tree-level-order-traversal/
public class LC102 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ret = new LinkedList<>();
        if (root == null) {
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()){
            List<Integer> temp = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                temp.add(node.val);
                if (node.left != null){
                    queue.add(node.left);
                }
                if (node.right != null){
                    queue.add(node.right);
                }
            }
            ret.add(temp);
        }
        return ret;
    }

    public static void main(String[] args) {
        // 构建一个二叉树：
        //        1
        //       / \
        //      2   3
        //     / \   \
        //    4   5   6
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.right = new TreeNode(6);

        // 创建 LevelOrderTraversal 对象
        LC102 traversal = new LC102();

        // 调用 levelOrder 方法并打印结果
        List<List<Integer>> result = traversal.levelOrder(root);

        // 输出应该是 [[1], [2, 3], [4, 5, 6]]
        System.out.println(result);
    }

}
